package com.adams.custom.page.core.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;

import com.adams.access.db.bean.DicColumn;
import com.adams.access.db.bean.DicTable;
import com.adams.core.exception.BusinessException;
import com.adams.custom.page.core.BusinessDealFlowAction;
import com.adams.custom.page.core.BusinessDealFlowContext;
import com.adams.custom.page.core.service.DicTableService;
import com.adams.custom.page.util.ViewUtil;

/**
 * 
 * File Name : DefaultSaveOrUpdateBusinessDeal.java
 * 
 * @Description : 默认增加或者更新数据业务处理
 * @author 904370 张汉辉
 */
public class DefaultSaveOrUpdateBusinessDeal implements BusinessDealFlowAction
{
	Logger logger = Logger.getLogger(DefaultSaveOrUpdateBusinessDeal.class
			.getName());

	/**
	 * Description : 表定义服务类 Author : 904370
	 */
	private DicTableService dicTableService;

	public void setDicTableService(DicTableService dicTableService)
	{
		this.dicTableService = dicTableService;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.adams.custom.page.core.BusinessDealFlowAction#invoke(com.adams.custom.page.core.BusinessDealFlowContext, java.lang.Object)
	 */
	@SuppressWarnings("unchecked")
	@Override
	public Object invoke(BusinessDealFlowContext businessContext,
			Object resultObject) throws BusinessException
	{

		logger.info("DefaultSaveOrUpdateBusinessDeal run method run begin.");
		String tablecode = businessContext.getTablecode();
		List<Map> inputMaps = businessContext.getInputMaps();
		List<Map> addInputMaps = new ArrayList<Map>();
		for (Map inputMap : inputMaps)
		{
			dicTableService.checkDataByCodeColumn(tablecode, inputMap);
			Map olddata = null;
			boolean itemHasKey = false;
			DicTable dicTable = dicTableService.getDicTable(tablecode);
			List<String> keycolumns = dicTable.getKeycolumnlist();
			if (null != keycolumns && keycolumns.size() > 0)
			{
				if (null != inputMap)
				{
					itemHasKey = true;
					for (String keycolumn : keycolumns)
					{
						if (!inputMap.containsKey(keycolumn))
						{
							itemHasKey = false;
							break;
						}
						Object value = inputMap.get(keycolumn);
						if (null == value
								|| ViewUtil.isNuLLStr(value.toString()))
						{
							itemHasKey = false;
							break;
						}
					}
				}
			}
			if (itemHasKey)
			{
				olddata = dicTableService.getDataByKey(tablecode, inputMap);
			}
			if (olddata == null)
			{
				// 把新增记录放入批量新增列表，提高新增性能
				addInputMaps.add(inputMap);

			} else
			{
				// 修改记录
				businessContext.setAttribute("olddata", olddata);
				updateDate(tablecode, inputMap, olddata);

			}
		}
		// 批量插入记录
		if (addInputMaps.size() > 0)
		{
			addDatas(tablecode, addInputMaps);

		}
		logger.info("DefaultSaveOrUpdateBusinessDeal run method run end.");
		// TODO Auto-generated method stub
		return inputMaps;
	}

	@SuppressWarnings("unchecked")
	private void updateDate(String tablecode, Map inputMap, Map olddata)
			throws BusinessException
	{
		Map newdata = null;
		newdata = new HashMap();
		Set key = olddata.keySet();
		for (Iterator cIt = key.iterator(); cIt.hasNext();)
		{
			String columncode = (String) cIt.next();
			if (!inputMap.containsKey(columncode))
			{
				newdata.put(columncode, olddata.get(columncode));
			} else
			{
				newdata.put(columncode, inputMap.get(columncode));
			}
		}
		// 更新本表
		dicTableService.updateData(tablecode, newdata, olddata);
	}

	@SuppressWarnings("unchecked")
	private void addDatas(String tablecode, List<Map> inputMaps)
			throws BusinessException
	{
		List<DicColumn> rddDicColumns = dicTableService
				.findRddcolumnByTablecode(tablecode);
		for (Map inputMap : inputMaps)
		{
			for (DicColumn rddDicColumn : rddDicColumns)
			{
				String columncode = rddDicColumn.getDicColumnPK()
						.getColumncode();
				String firstRddrelcolumn = rddDicColumn.getFirstRddrelcolumn();
				List<String> rddrelcolumns = rddDicColumn.getRddrelcolumns();
				rddrelcolumns.remove(0);
				if (inputMap.containsKey(firstRddrelcolumn))
				{
					Object keyValue = inputMap.get(firstRddrelcolumn);
					if (null != keyValue)
					{
						String keyValueStr = keyValue.toString();
						if (!ViewUtil.isNuLLStr(keyValueStr))
						{
							DicColumn firstDicColumn = dicTableService
									.getDicColumn(tablecode, firstRddrelcolumn);
							String sourcetable = firstDicColumn
									.getSourcetable();
							DicTable sourceDicTable = dicTableService
									.getDicTable(sourcetable);
							String keycolumn = sourceDicTable.getKeycolumns();
							Map beanMap = new HashMap();
							beanMap.put(keycolumn, keyValueStr);
							// 增加冗余字段值
							Object value = dicTableService
									.findValueByTableCodeAndColumncodes(
											sourcetable, rddrelcolumns, beanMap);
							inputMap.put(columncode, value);
						}
					}
				}
			}
		}
		dicTableService.saveDatas(tablecode, inputMaps);
	}
}
